package ck

import (
	"gitee.com/tietang/terrace-go/v2/example/moni/dao"
	"gitee.com/tietang/terrace-go/v2/lib/rpc"
	"github.com/sirupsen/logrus"
	"github.com/tietang/dbx"
)

var ckJvmDetailDao *ClickHouseJvmDetailDao = new(ClickHouseJvmDetailDao)

func init() {
	//dao.Register("jvm.JvmDetailInfo", ckJvmDetailDao)
	handler := dao.NewHandler(ckJvmDetailDao)
	rpc.RegisterHandler("jvm.JvmDetailInfo", handler)
}

type ClickHouseJvmDetailDao struct {
}

const SysType = 0
const JvmType = 1

func (d *ClickHouseJvmDetailDao) Save(metrics any) {
	met := metrics.(map[string]interface{})
	systemDetail := met["systemDetail"].(map[string]interface{})

	args := make([]interface{}, 0, 32)
	for key, val := range systemDetail {
		args = append(args, met["appName"])
		args = append(args, met["hostName"])
		args = append(args, met["env"])
		args = append(args, SysType)
		args = append(args, met["timestamp"])
		args = append(args, key)
		args = append(args, val)
	}
	jvmDetail := met["jvmDetail"].(map[string]interface{})
	for key, val := range jvmDetail {
		args = append(args, met["appName"])
		args = append(args, met["hostName"])
		args = append(args, met["env"])
		args = append(args, JvmType)
		args = append(args, met["timestamp"])
		args = append(args, key)
		args = append(args, val)
	}

	Clickhouse().Tx(func(run *dbx.TxRunner) error {
		_, err := run.Exec(JvmDetailSql, args...)
		if err != nil {
			logrus.Error(err)
			return err
		}
		return nil
	})

}

func (d *ClickHouseJvmDetailDao) Init() {

	Clickhouse().Tx(func(run *dbx.TxRunner) error {
		run.Exec(JvmDetailCreateTable)
		return nil
	})
}

const JvmDetailSql = "INSERT INTO m_jvm_props (  appName,hostName,env,type,ts,key,value) " +
	//" from input (' appName String,  hostName String,  env String,  type Int64, ts UInt64, key String,  value String')";
	" values (?,?,?,?,?,?,?)"

const JvmDetailCreateTable = "create table if not exists m_jvm_props" +
	" (" +
	" appName String," +
	" hostName String," +
	" env String," +
	" type Int," +
	" ts UInt64," +
	" key String," +
	" value String," +
	" d Date materialized toDate(round(ts / 1000))," +
	" dt DateTime materialized toDateTime(round(ts / 1000))" +
	" )  engine = MergeTree PARTITION BY (toYYYYMM(dt), appName)\n" +
	"        ORDER BY dt\n" +
	"        SETTINGS index_granularity = 8192;"
